package com.xinqi.modules.mq.rongyun.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.xinqi.common.core.constant.ChatConstants;
import com.xinqi.common.core.constant.ChatRemindConstants;
import com.xinqi.common.core.enums.RocketMqEnum;
import com.xinqi.common.core.enums.RocketMqRongyunEnum;
import com.xinqi.common.rocketmq.dto.ChatMessageMessageBody;
import com.xinqi.common.rocketmq.dto.RocketMqBean;
import com.xinqi.common.rocketmq.util.ByteUtils;
import com.xinqi.modules.chat.chat.group.message.GroupNoticeMessage;
import com.xinqi.modules.chat.chat.official.dto.rsp.ChatAssistantContentMessageResultDTO;
import com.xinqi.modules.chat.chat.official.json.ChatRemindMessage;
import com.xinqi.modules.mq.rongyun.third.service.RongyunService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.apis.*;
import org.apache.rocketmq.client.apis.consumer.FilterExpression;
import org.apache.rocketmq.client.apis.consumer.FilterExpressionType;
import org.apache.rocketmq.client.apis.consumer.SimpleConsumer;
import org.apache.rocketmq.client.apis.consumer.SimpleConsumerBuilder;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @version V1.0
 * @Title: 融云--消息类MQ消息监听
 * @ClassName: com.xinqi.modules.chat.mq.consumer.RongyunMessageConsumer.java
 * @Description:
 * @Copyright 星齐科技（云南）有限公司 - Powered By 技术部
 * @author: yyzhen
 * @date: 2023/8/1 9:38
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RongyunMessageConsumer {

    private final RongyunService rongyunService;

    @Async
    public void pushMessageConsumerMsg(RocketMqBean rocketMqBean, RocketMqEnum mqEnum) throws ClientException {
        log.info("融云--消息类MQ消息监听启动 => {}", mqEnum);
        ClientServiceProvider provider = ClientServiceProvider.loadService();

        SessionCredentialsProvider sessionCredentialsProvider =
            new StaticSessionCredentialsProvider(rocketMqBean.getUsername(), rocketMqBean.getPassword());

        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
            .setEndpoints(rocketMqBean.getEndpoints())
            .setCredentialProvider(sessionCredentialsProvider)
            .build();
        Duration awaitDuration = Duration.ofSeconds(30);
        FilterExpression filterExpression = new FilterExpression(mqEnum.getCode(), FilterExpressionType.TAG);
        SimpleConsumerBuilder simpleConsumerBuilder = provider.newSimpleConsumerBuilder()
            .setClientConfiguration(clientConfiguration)
            .setConsumerGroup(mqEnum.getCode())
            .setAwaitDuration(awaitDuration)
            .setSubscriptionExpressions(Collections.singletonMap(rocketMqBean.getTopic(), filterExpression));
        try {
            startConsumer(simpleConsumerBuilder);
        } catch (Exception e) {
            startConsumer(simpleConsumerBuilder);
        }
    }

    /**
     * 启动消费服务
     * @author dzy
     */
    private void startConsumer(SimpleConsumerBuilder simpleConsumerBuilder) throws ClientException {
        SimpleConsumer consumer = simpleConsumerBuilder.build();
        // Max message num for each long polling.
        int maxMessageNum = 20;
        // Set message invisible duration after it is received.
        Duration invisibleDuration = Duration.ofSeconds(10);
        do {
            List<MessageView> messages = consumer.receive(maxMessageNum, invisibleDuration);
            log.info("RONGYUN_MESSAGE => 本次获取 {} 条message", messages.size());
            for (MessageView messageView : messages) {
                try {
                    //MQ消息校验
                    String message = ByteUtils.byteBufferToStr(messageView.getBody());
                    if (StringUtils.isEmpty(message)) {
                        consumer.ack(messageView);
                    }
                    JSONObject json = JSONObject.parseObject(message);
                    if (Objects.isNull(json)) {
                        consumer.ack(messageView);
                    }
                    boolean flag = processingMessages(json);
                    if (flag) {
                        consumer.ack(messageView);
                    }
                } catch (Throwable t) {
                    log.error("融云 -- 消息类MQ消费消息异常 => {}", messageView);
                }
            }
        } while (true);
    }

    /**
     * 根据类型区分业务处理
     *
     * @param json
     * @return
     */
    private boolean processingMessages(JSONObject json) {
        boolean flag = Boolean.TRUE;
        //业务类型区分
        String type = json.getString("type");
        if (StringUtils.isEmpty(type)) {
            return flag;
        }
        //业务处理
        if (Objects.equals(RocketMqRongyunEnum.RONGYUN_REMIND_MESSAGE.getCode(), type)) {
            //融云--新奇提醒
            flag = sendRemind(JSONObject.parseObject(json.toJSONString(), ChatMessageMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_ASSISTANT_MESSAGE.getCode(), type)) {
            //融云--课程助手
            flag = sendAssistant(JSONObject.parseObject(json.toJSONString(), ChatMessageMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_ASSISTANT_UPDATE_MESSAGE.getCode(), type)) {
            //融云--课程助手
            flag = sendUpdateAssistant(JSONObject.parseObject(json.toJSONString(), ChatMessageMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_SYSTEM_MESSAGE.getCode(), type)) {
            //融云--系统--通知消息
            flag = sendSystem(JSONObject.parseObject(json.toJSONString(), ChatMessageMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_GROUP_MESSAGE.getCode(), type)) {
            //融云--群聊--通知消息
            flag = sendGroup(JSONObject.parseObject(json.toJSONString(), ChatMessageMessageBody.class));
        }

        return flag;
    }

    /**
     * 融云--新奇提醒
     *
     * @param body
     * @return
     */
    private boolean sendRemind(ChatMessageMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        ChatRemindMessage message = JSONObject.parseObject(body.getJson(), ChatRemindMessage.class);
        if (Objects.isNull(message)) {
            return Boolean.TRUE;
        }
        String[] targetIds = body.getTargetIds();
        if (Objects.isNull(targetIds) || targetIds.length == 0) {
            return Boolean.TRUE;
        }
        return rongyunService.sentRemindMsg(ChatRemindConstants.REMIND, ChatRemindConstants.REMIND_OBJECT_NAME, targetIds, message);
    }

    /**
     * 融云--课程助手
     *
     * @param body
     * @return
     */
    private boolean sendAssistant(ChatMessageMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        String[] targetIds = body.getTargetIds();
        if (Objects.isNull(targetIds) || targetIds.length == 0) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getJson())) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getObjectName())) {
            return Boolean.TRUE;
        }
        return rongyunService.sentOfficialExtMsg(body.getSenderId(), body.getObjectName(), targetIds, body.getJson(), body.getPushContent());
    }

    /**
     * 融云--课程助手
     *
     * @param body
     * @return
     */
    private boolean sendUpdateAssistant(ChatMessageMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        String[] targetIds = body.getTargetIds();
        if (Objects.isNull(targetIds) || targetIds.length == 0) {
            return Boolean.TRUE;
        }
        ChatAssistantContentMessageResultDTO message = JSONObject.parseObject(body.getJson(), ChatAssistantContentMessageResultDTO.class);
        if (Objects.isNull(message)) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getObjectName())) {
            return Boolean.TRUE;
        }
        return rongyunService.sentUpdateOfficialExtMsg(ChatRemindConstants.ASSISTANT, body.getObjectName(), targetIds, message);
    }

    /**
     * 融云--系统--通知消息
     *
     * @param body
     * @return
     */
    private boolean sendSystem(ChatMessageMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getJson())) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getSenderId())) {
            return Boolean.TRUE;
        }
        String[] targetIds = body.getTargetIds();
        if (Objects.isNull(targetIds) || targetIds.length == 0) {
            return Boolean.TRUE;
        }
        return rongyunService.sentSystemCmdMsg(body.getSenderId(), targetIds, body.getJson());
    }

    /**
     * 融云--群聊--通知消息
     *
     * @param body
     * @return
     */
    private boolean sendGroup(ChatMessageMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        GroupNoticeMessage message = JSONObject.parseObject(body.getJson(), GroupNoticeMessage.class);
        if (Objects.isNull(message)) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getSenderId())) {
            return Boolean.TRUE;
        }
        String[] targetIds = body.getTargetIds();
        if (Objects.isNull(targetIds) || targetIds.length == 0) {
            return Boolean.TRUE;
        }
        return rongyunService.sentGroupMsg(body.getSenderId(), ChatConstants.CHAT_GROUP_NOTICE_OBJECT_NAME, targetIds, message);
    }


}
